package com.whoisaa.wifitransfer;

import android.content.Context;
import android.os.Handler;

import com.whoisaa.wifitransfer.base.BaseThread;
import com.whoisaa.wifitransfer.bean.FileInfo;
import com.whoisaa.wifitransfer.bean.Header;
import com.whoisaa.wifitransfer.ui.activity.ReceiverActivity;
import com.whoisaa.wifitransfer.utils.AppUtils;
import com.whoisaa.wifitransfer.utils.FileUtils;
import com.whoisaa.wifitransfer.utils.L;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 接收端线程
 * @Author AA
 * @DateTime 16/4/19 下午6:05
 */
public class WifiClientThread extends BaseThread {

    private Context mContext;
    private Handler mHandler;
    private Socket mSocket;
    private IClientConnectionListener mConnectionListener;

    private String mIp;
    public static final int TIMEOUT = 10 * 1000;


    public WifiClientThread(Context context, Handler handler, String ip, IClientConnectionListener listener) {
        this.mContext = context;
        this.mHandler = handler;
        this.mIp = ip;
        this.mConnectionListener = listener;
    }

    @Override
    public void run() {
        try {
            currentThread();
            sleep(1000);
            mSocket = new Socket(mIp, SERVERPOST);
            if (mSocket != null && mConnectionListener != null) {
//                //保持连接
//                mSocket.setKeepAlive(true);
//                //设置超时为10秒
//                mSocket.setSoTimeout(TIMEOUT);
                OutputStream os = mSocket.getOutputStream();
                os.write(AppUtils.getMobileModel().getBytes(UTF_8));
                os.flush();
                mConnectionListener.onSuccess(mSocket);

            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
            if (mConnectionListener != null) {
                mConnectionListener.onFailure(e);
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (mConnectionListener != null) {
                mConnectionListener.onFailure(e);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            if (mConnectionListener != null) {
                mConnectionListener.onFailure(e);
            }
        }
    }

    public void receive() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //是否全部接收完毕
                boolean isFinish = false;
                if (mSocket != null) {
                    try {
                        final InputStream is = mSocket.getInputStream();
                        OutputStream os = mSocket.getOutputStream();

                        //获取文件名和文件大小
                        byte[] headerData = new byte[buf_size];
                        int len = is.read(headerData);
                        if (len != -1) {
                            Header header = getHeader(new String(headerData, 0, len, UTF_8));
                            if (header != null && header.getFileInfos() != null && header.getFileInfos().size() > 0) {
                                sendMessage(mHandler, ReceiverActivity.INIT_ADAPTER, header.getFileInfos());
                                //告知发送端开始发送
                                os.write("start".getBytes(UTF_8));
                                os.flush();

                                //准备接收
                                String fileDir = FileUtils.getReceiveFilesPath();
                                for (int i = 0; i < header.getFileTotalCount(); i++) {
                                    FileInfo fileInfo = header.getFileInfos().get(i);
                                    String filename = fileInfo.getFileName();
                                    long totalSize = fileInfo.getFileLength();
                                    sendMessage(mHandler, 10, "准备接收: 文件名: " + filename + " 文件大小: " + totalSize);

                                    //如果文件不存在,创建它
                                    File file = new File(fileDir + filename);
                                    if (!file.exists()) {
                                        file.getParentFile().mkdirs();
                                        file.createNewFile();
                                    }
                                    DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
                                    byte[] recvData = new byte[file_buf_size];
                                    int receiveLen = 0;
//                                    while ((len = is.read(recvData)) != -1) {
//                                        dos.write(recvData, 0, len);
//                                        receiveLen += len;
//                                        int progress = (int) (receiveLen * 100 / totalSize);
//                                        sendMessage(mHandler, ReceiverActivity.REFRESH_PROGRESS, i, progress);
//                                        L.error("文件(" + filename + ") 总大小: " + totalSize + " 已接收文件(" + progress + "): " + receiveLen);
//
//                                        if(progress == 100) {
//                                            break;
//                                        }
//                                    }

                                    int timeout = 0;
                                    while (true) {
                                        if((len = is.read(recvData)) == -1) {
                                            L.error("~~~~~~~~~~~~~~~已经接收了" + receiveLen + ", 还剩:" + (totalSize - receiveLen));
                                            if(timeout < 5) {
                                                timeout++;
                                                continue;
                                            } else {
                                                break;
                                            }
                                        }
                                        long tmpLen = totalSize - receiveLen - len;
                                        if(tmpLen <= file_buf_size && tmpLen > 0) {
                                            L.error("************* Lenght 小于1024 -- --" + tmpLen);
                                            dos.write(recvData, 0, (int) tmpLen);
                                            receiveLen += tmpLen;
                                        } else {
                                            L.error("************* Lenght 大于1024 -- --" + len);
                                            dos.write(recvData, 0, len);
                                            receiveLen += len;
                                        }

                                        int progress = (int) (receiveLen * 100 / totalSize);
                                        sendMessage(mHandler, ReceiverActivity.REFRESH_PROGRESS, i, progress);
                                        L.error("文件(" + filename + ") 总大小: " + totalSize + " 已接收文件(" + progress + "): " + receiveLen);

                                        if(progress == 100) {
                                            break;
                                        }
                                    }

                                    //文件大小不一致
                                    if (receiveLen != totalSize) {
                                        sendMessage(mHandler, 10, "文件大小不一致");
                                    }

                                    dos.flush();
                                    dos.close();
                                }
                                //全部接收完毕
                                isFinish = true;
                                os.close();
                                is.close();
                            }
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                        isFinish = false;
                        sendMessage(mHandler, 10, "接收失败: " + e.getMessage());
                    } catch (IOException e) {
                        e.printStackTrace();
                        isFinish = false;
                        sendMessage(mHandler, 10, "接收失败: " + e.getMessage());
                    } finally {
                        try {
                            //关闭Socket
                            mSocket.close();
                        } catch (IOException e) {
                            isFinish = false;
                            e.printStackTrace();
                        }

                        if (isFinish) {
                            sendMessage(mHandler, 10, "全部接收完毕");
                        } else {
                            sendMessage(mHandler, 10, "接收出错");
                        }
                    }
                }
            }
        }).start();
    }

    /**
     * 字符串解析Header实体类
     *
     * @param headerStr
     * @return
     */
    private Header getHeader(String headerStr) {
        Header header = new Header();
        String[] headerStrs = headerStr.split(Header.separator);
        if (headerStrs.length == 3) {
            header.setMobileModel(headerStrs[0]);
            header.setFileTotalCount(Integer.parseInt(headerStrs[1]));
            String[] fileInfos = headerStrs[2].split(Header.file_separator2);
            if (fileInfos.length > 0) {
                List<FileInfo> fileFolderList = new ArrayList<>();
                for (String fileInfoStr : fileInfos) {
                    String[] tmps = fileInfoStr.split(Header.file_separator);
                    if (tmps.length == 2) {
                        fileFolderList.add(new FileInfo(tmps[0], Integer.parseInt(tmps[1])));
                    }
                }
                header.setFileInfos(fileFolderList);
            }
            L.error("Header = " + header.toString());
        }
        return header;
    }
}
